package com.test.booksystem.controller;

import com.test.booksystem.constant.Constants;
import com.test.booksystem.model.UserInfo;
import com.test.booksystem.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// 用户的登录
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public String login(String userName, String password, HttpSession session) {
        // 校验账户和密码是否为空
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return "用户名或密码为空！";
        }
        // 从 Service 层获取到用户名
        UserInfo userInfo = userService.getUserName(userName);
        if (userInfo == null) {
            return "用户不存在";
        }
        // 若用户是存在的，则判定密码是否正确
        if (!password.equals(userInfo.getPassword())) {
            return "密码错误";
        }
        // 存储session信息：用户的整个信息
        session.setAttribute(Constants.USER_INFO, userInfo);
        // 均正确返回空
        return "";
    }
}
